import zsh.service.IService;
import zsh.service.ServiceImpl;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/deleteStudent")
public class DeleteStudent extends HttpServlet {
    private IService studentService = new ServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        // 1. 获取输入流
        BufferedReader reader = req.getReader();
        // 2. 获取请求的完整信息
        StringBuilder requestBodyJsonStr = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            requestBodyJsonStr.append(line);
        }
        // 3, 将字符串信息解析承json对象
        Student student = JSONObject.parseObject(requestBodyJsonStr.toString(), Student.class);

        try {
            if (student != null) {
                studentService.deleteStudent(student.getId());
                resp.setStatus(HttpServletResponse.SC_NO_CONTENT); // 204 No Content
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); // 404 Bad Request
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}